package com.sline.day01.jdbc;

import java.sql.*;

public class Demo4_DQL {
    public static void main(String[] args) throws Exception {
        demo3();
    }

    private static void demo1() throws Exception {
        String sql = "select id from t_student;";

        // 加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 创建数据库连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "admin");

        // 创建语句对象
        Statement statement = connection.createStatement();

        // 执行sql
        ResultSet rs = statement.executeQuery(sql);
        while (rs.next()) {
            long sid = rs.getLong("id");
            System.out.println("id是" + sid);
        }

        // 释放资源
        rs.close();
        statement.close();
        connection.close();
    }

    private static void demo2() throws Exception {
        String sql = "select * from t_student where id = 1;";

        //加连语执释
        Class.forName("com.mysql.jdbc.Driver");

        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "admin");

        Statement statement = connection.createStatement();

        ResultSet rs = statement.executeQuery(sql);

        if (rs.next()) {
            long sid = rs.getLong("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");

            System.out.println(sid + ", " + name + ", " + age);
        }

        rs.close();
        statement.close();
        connection.close();
    }

    private static void demo3() throws Exception {
        String sql = "select * from t_student";

        // 加连语执释
        Class.forName("com.mysql.jdbc.Driver");

        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "admin");

        Statement statement = connection.createStatement();

        ResultSet rs = statement.executeQuery(sql);
        while (rs.next()) {
            long sid = rs.getLong("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");

            System.out.println(sid + ", " + name + ", " + age);
        }

        rs.close();
        statement.close();
        connection.close();
    }

}
